﻿var isIE = navigator.userAgent.indexOf('MSIE') != -1;
var isIE6 = isIE && ([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == "6");

var AjaxTree = Class.create({
	initialize:function(url,options){
		var self = this;
		var aURL = url.indexOf('?') == -1 ? url+'?ajax__r='+Math.random() : url+'&ajax__r='+Math.random();
		this.url = url;
		this.treeConfig = {		//初始配置表
			id:'',				//容器ID
			selector:true,		//是否作为下拉菜单
			action:true			//是否显示'新增,编辑,删除'动作
		};
		
		//console.info(typeof options);
		if(typeof options == 'object'){
			Object.extend(this.treeConfig,options);
		}
		
		this.obj = $(this.treeConfig.id);
		var tId = this.obj.id;
		var act = this.obj.action;
		var pos = getPos($(this.treeConfig.id));

		if(this.treeConfig.selector){  //作为下拉菜单呈现
			this.obj.observe('click',function(event){
				stopBubble(event);
				
				if($('bind'+this.id)){ 
					$('bind'+this.id).remove();
					return;
				}
				
				var div = document.createElement('div');
				div.id = 'bind'+this.id;
				div.className = 'treeBox';
				div.style.left = parseInt(pos.left) + 'px';
				div.style.top = parseInt(pos.bottom) + 'px';
				div.innerHTML = 'Loading...';
				document.body.appendChild(div);
				
				var treeBox = $('bind'+this.id);
				
				new Ajax.Request(aURL,{
								
					onSuccess: function(resp){
						
						treeBox.update(resp.responseText);
						
						document.body.onclick = function(event){  //鼠标点击页面其他地方时，删除tree
							
							if(!treeBox) {return;}
							var event = window.event || event;
							var target = Event.element(event);
							
							if(!target.ancestors().pluck('id').include('bind'+tId)){
								treeBox.innerHTML = '';
								treeBox.remove();
								//if($('overFrame')) document.body.removeChild($('overFrame'));
							}
						};
						
						//self.t();
						regAll();
						self.regAction();
						self.regSelect();
						
					}
				});
			});
		}else{   //作为一般容器呈现
			var treeBox = $(this.treeConfig.id);
			treeBox.update('Loading...');
			new Ajax.Request(aURL,{
				onSuccess: function(resp){
					//console.info(resp.responseText);
					treeBox.update(resp.responseText);
					regAll();
					self.regAction();
					self.regSelect();
				}
			});
		}
	},
	
	addNode: function(o,e){
		Event.stop(e);
		var reUrl = o.getAttribute('href');
		var self = this;
		var layer = createOverLayer();
		layer.id = 'overlayer';
		layer.style.zIndex = 1000;
		
		var div = document.createElement('div');
		div.id = 'inputBox';
		div.style.zIndex = 1001;
		
		var form = document.createElement('form');
		form.id = 'form';
		//form.style.padding = '10px';
		var i18n = eval('('+ $('i18n').value +')');  //获取国际化文本
		
		var content = "<div><input type='radio' id='branchBt' name='nodeType' checked='checked' /><label for='branchBt'>"+ i18n['addBranch'] +"</label>";
		content += "<input type='radio' id='leafBt' name='nodeType' /><label for='leafBt'>"+ i18n['addLeaf'] +"</label></div>";
		content += "<div id='branchBox'>"+ i18n['name'] +":<input type='text' id='branchValue' /></div>";
		content += "<div id='leafBox' style='display:none'><p>"+ i18n['name'] +":<input type='text' id='leafValue' /></p>";
		content += "<p>"+ i18n['ip'] +":<input type='text' class='ipValue' /><span onclick='addInput()'>[+]</span></p></div>";
		content += "<input type='button' id='addOk' value='"+ i18n['ok'] +"' /> <input type='button' id='addCancel' value='"+ i18n['cancel'] +"' />";
		form.innerHTML = content;
		
		div.appendChild(form);
		hideSelect();
		document.body.appendChild(div);
		document.body.appendChild(layer);
		
		regAll();
		
		$('branchBt').onclick = function(){
			$('branchBox').style.display = '';
			$('leafBox').style.display = 'none';
		}
		
		$('leafBt').onclick = function(){
			$('branchBox').style.display = 'none';
			$('leafBox').style.display = '';
		}
		
		$('addOk').onclick = function(){
			
			if($('leafBt').checked){  //添加叶
				new Ajax.Request(reUrl,{
					method:'post',
					parameters:'name='+$F('leafValue')+'&ip={ip:'+$$("#leafBox .ipValue").pluck("value").toJSON()+'}',
					onSuccess: function(resp){
						var li = createLi(self.treeConfig.action);
						if(o.parentNode.down('ul')){
							o.parentNode.down('ul').appendChild(li);
						}else{
							var ul = document.createElement('ul');
							ul.appendChild(li);
							o.parentNode.appendChild(ul);
						}
						showSelect();
					},
					onFailure: function(){
						alert('请求未成功，请继续尝试');
					}
				});
			}
			if($('branchBt').checked){ //添加枝
				new Ajax.Request(reUrl,{
					method:'post',
					parameters:'name='+$F('branchValue'),
					onSuccess: function(resp){
						var li = createLi2(self.treeConfig.action);
						if(o.parentNode.down('ul')){
							o.parentNode.down('ul').appendChild(li);
						}else{
							var ul = document.createElement('ul');
							ul.appendChild(li);
							o.parentNode.appendChild(ul);
						}
						showSelect();
					},
					onFailure: function(){
						alert('请求未成功，请继续尝试');
					}
				});
			}
			self.regSelect();
			self.regAction();
			regAll();
			$('inputBox').innerHTML = '';
			document.body.removeChild($('inputBox'));
			document.body.removeChild($('overlayer'));
		}.bind(this,o);
		
		$('addCancel').onclick = function(event){
			showSelect();
			$('inputBox').innerHTML = '';
			document.body.removeChild($('inputBox'));
			document.body.removeChild($('overlayer'));
		};
		
		$('inputBox').onclick = function(event){
			stopBubble(event);
		};
		
		$('overlayer').onclick = function(event){
			stopBubble(event);
		};
		
		$('inputBox').style.margin = (document.documentElement.scrollTop - getPos($('inputBox')).height/2)+'px 0 0 '+ parseInt(document.documentElement.scrollLeft - getPos($('inputBox')).width/2)+'px';
	},
	
	editNode: function(o,e){
		Event.stop(e);
		var reUrl = o.getAttribute('href');
		var self = this;
		var i18n = eval('('+ $('i18n').value +')');  //获取国际化文本
		var form = document.createElement('form');
		form.id = 'form';
		//form.style.padding = '10px';
		
		var div = document.createElement('div');
		div.id = 'inputBox';
		div.style.zIndex = 1001;
		
		var layer = createOverLayer();
		layer.id = 'overlayer';
		layer.style.zIndex = 1000;
		
		if(o.siblings().length > 2){ //节点为枝时的处理
			
			var n1 = createTag({tagName:'input',value:o.parentNode.down().innerHTML,id:'parentName'});
			var bt1 = createTag({tagName:'input',type:'button',value:'OK',id:'editOk'});
			var bt2 = createTag({tagName:'input',type:'button',value:'Cancell',id:'editCancel'});
			
			form.appendChild(n1);
			form.appendChild(bt1);
			form.appendChild(bt2);
			
			div.appendChild(form);
			hideSelect();
			document.body.appendChild(div);
			document.body.appendChild(layer);
			regAll();
			
			$('editOk').onclick = function(event){
				new Ajax.Request(reUrl,{
					method:'post',
					parameters:'name='+$F('parentName'),
					onSuccess: function(resp){
						o.parentNode.down().innerHTML = $F('parentName');
					},
					onFailure: function(){
						alert('请求未成功，请继续尝试');
					}
				});
				$('inputBox').innerHTML = '';
				document.body.removeChild($('inputBox'));
				document.body.removeChild($('overlayer'));
				showSelect();
			};
			
			$('editCancel').onclick = function(event){
				$('inputBox').innerHTML = '';
				document.body.removeChild($('inputBox'));
				document.body.removeChild($('overlayer'));
				showSelect();
			}
		}else{ //节点为叶子时的处理
			var arr = eval('('+ o.parentNode.down().down().value +')');
			//console.info(arr);
			var str = "<div id='leafBox'><p>"+ i18n['ip'] +": <input class='ipValue' type='text' value='"+ arr["ip"][0] +"' /><span onclick='addInput()'>[+]</span></p>";
			for(var i = 1,len = arr['ip'].length;i < len; i++){
				str += "<p>"+ i18n['ip'] +": <input class='ipValue' type='text' value='"+ arr["ip"][i] +"' /><span onclick='delInput(this)'>[-]</span></p>";
			}
			str += "</div><input type='button' id='editOk' value='"+ i18n['ok'] +"' /> <input type='button' id='editCancel' value='"+ i18n['cancel'] +"' />";
	
			form.innerHTML = str;
			
			div.appendChild(form);
			hideSelect();
			document.body.appendChild(layer);
			document.body.appendChild(div);
			regAll();
			
			$('editOk').onclick = function(event){
				new Ajax.Request(reUrl,{
					method:'post',
					parameters:'ip={ip:'+ $$("#leafBox .ipValue").pluck("value").toJSON() +'}',
					onSuccess: function(resp){
						o.parentNode.down().down('input').value = '{ip: '+ $$('#leafBox .ipValue').pluck('value').toJSON() +'}';
					},
					onFailure: function(){
						alert('请求未成功，请继续尝试');
					}
				});
				document.body.removeChild($('inputBox'));
				document.body.removeChild($('overlayer'));
				showSelect();
			};
			
			$('editCancel').onclick = function(event){
				document.body.removeChild($('inputBox'));
				document.body.removeChild($('overlayer'));
				showSelect();
			};
		}
		
		$('inputBox').onclick = function(event){ //阻止事件冒泡
			stopBubble(event);
		}
		
		$('overlayer').onclick = function(event){ //阻止事件冒泡
			stopBubble(event);
		}
		//弹出DIV居中
		$('inputBox').style.margin = (document.documentElement.scrollTop - getPos($('inputBox')).height/2)+'px 0 0 '+ parseInt(document.documentElement.scrollLeft - getPos($('inputBox')).width/2)+'px';
	},
	
	regSelect: function(){
		var self = this;
		//console.info($$('#bind'+this.treeConfig.id+' span'));
		if(self.treeConfig.selector){
			$$('#bind'+this.treeConfig.id+' span').each(function(node){   // 选择tree叶子中的值到Input或展开枝
				node.onclick = function(){
					if(this.parentNode.down('ul')){
						
						this.parentNode.down('ul').toggle();
					}
					else{
						$(self.treeConfig.id).value = this.innerHTML.replace(/<.+?>/gim,'');
						document.body.removeChild($('bind'+self.treeConfig.id));
					}
				}
			});
			
			$$('#bind'+this.treeConfig.id+' span').each(function(node){   // 双击选择枝的值到input
				node.ondblclick = function(){
					$(self.treeConfig.id).value = this.innerHTML.replace(/<.+?>/gim,'');
					document.body.removeChild($('bind'+self.treeConfig.id));
				}
			});
		}else{
			$$('#'+this.treeConfig.id+' span').each(function(node){   // 选择tree叶子中的值到Input或展开枝
				node.onclick = function(){
					if(this.parentNode.down('ul')){
						this.parentNode.down('ul').toggle();
					}
				}
			});
		}
	},
	
	regAction: function(event){
		var self = this;
		var addBts = this.treeConfig.selector ? $$('#bind'+this.treeConfig.id+' a.addBt') : $$('#'+this.treeConfig.id+' a.addBt');
		var editBts = this.treeConfig.selector ? $$('#bind'+this.treeConfig.id+' a.editBt') : $$('#'+this.treeConfig.id+' a.editBt');
		var delBts = this.treeConfig.selector ? $$('#bind'+this.treeConfig.id+' a.deleteBt') : $$('#'+this.treeConfig.id+' a.deleteBt');
		if(!this.treeConfig.action){
			addBts.invoke('hide');
			editBts.invoke('hide');
			delBts.invoke('hide');
			return;
		}
		addBts.each(function(node){
			node.onclick = function(event){
				var e = window.event || event;
				//alert(e.type);
				//e.stop();
				Event.stop(e);
				self.addNode(this,e);
			};
		});
		
		editBts.each(function(node){
			node.onclick = function(event){
				var e = window.event || event;
				Event.stop(e);
				self.editNode(this,e);
			}
		});
		
		delBts.each(function(node){
			node.onclick = function(event){
				var e = window.event || event;
				Event.stop(e);
				this.parentNode.remove();
			}
		});
	}
});


function getPos(o){
	var pos = {};
	pos.top = o.getBoundingClientRect().top + document.documentElement.scrollTop;
	pos.left = o.getBoundingClientRect().left + document.documentElement.scrollLeft;
	pos.right = o.getBoundingClientRect().right + document.documentElement.scrollLeft;
	pos.bottom = o.getBoundingClientRect().bottom + document.documentElement.scrollTop;
	pos.width = pos.right - pos.left;
	pos.height = pos.bottom - pos.top;
	return pos;
}

function addInput(){
	var i18n = eval('('+ $('i18n').value +')');
	var p = document.createElement('p');
	p.innerHTML = i18n['ip'] +": <input type='text' class='ipValue'><span onclick='delInput(this)'>[-]</span>";
	$('leafBox').appendChild(p);
	regAll();
}

function delInput(o){
	o.parentNode.parentNode.removeChild(o.parentNode);
}

function createLi(cf){
	//console.info('<input type="hidden" value=\'{ip:'+$$('#leafBox .ipValue').pluck('value').toJSON()+'}\' />');
	var i18n = eval('('+ $('i18n').value +')');
	var li = document.createElement('li');
	var str = '<span>'+$F('leafValue');
	if(cf) str += '<input type="hidden" value=\'{ip:'+$$('#leafBox .ipValue').pluck('value').toJSON()+'}\' /></span><a href="edit.php" class="editBt">编辑</a> <a href="delete.php" class="deleteBt">删除</a>';
	li.innerHTML = str;
	return li;
}

function createLi2(cf){
	var i18n = eval('('+ $('i18n').value +')');
	var li = document.createElement('li');
	var str = '<span>'+$F('branchValue');
	if(cf) str += '</span><a href="add.php" class="addBt">新增</a> <a href="edit.php" class="editBt">编辑</a ><a href="delete.php" class="deleteBt">删除</a>';
	li.innerHTML = str;
	return li;
}

function hideSelect(){
	if(isIE6) $$('select').invoke('hide');
}

function showSelect(){
	$$('select').invoke('show');
}

function regAll(){ //使IE下的元素继承prototype的Element
	if (document.all) {
		$A(document.all).each(function(element) {
			Element.extend(element);
		});
	}
}

function createFragment(){
	return document.createDocumentFragment();
}

function createOverLayer(){
	var layer = document.createElement('div');
	layer.className = 'overLayer';
	layer.style.width = Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth) + 'px';
	layer.style.height = Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight) + 'px';
	return layer;
}

function createTag(){
	var attr = arguments[0];
	var tag = document.createElement(attr.tagName);
	//if(typeof attr == 'Object'){
		for(var i in attr){
			if(i == 'class'){
				tag.className = attr[i];
			}else if(i != 'tagName'){
				tag.setAttribute(i,attr[i]);
			}
		}
	//}
	return tag;
}

function stopBubble(e){
	var e = window.event || e;
	if(e.stopPropagation){
		e.stopPropagation();
	}else{
		e.cancelBubble = true;
	}
}

document.observe('dom:loaded',regAll);

